package com.winit.needcustomers.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.winit.commons.util.HttpClientUtil;
import com.winit.needcustomers.model.NeedCustomer;
import com.winit.needcustomers.web.NeedCustomerController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class FetchCustomersService {

    private static Logger log = LoggerFactory.getLogger(FetchCustomersService.class);

    @Autowired
    protected RedisTemplate<String, Object> redisTemplate;

    @Value("${fecth_customer_url}")
    private String fecth_customer_url;

    @Scheduled(fixedRate = 1000 * 60 * 60 * 24)
    public void fetchCustomers() {
        flushAndLoadCustomers();
    }


    /**
     * 刷新用户数据
     */
    public void flushAndLoadCustomers() {
        List<NeedCustomer> needCustomers = Lists.newArrayList();
        try {
            redisTemplate.opsForList().getOperations().expire("needCustomers", 0, TimeUnit.MILLISECONDS);
            JSONObject jsonObject = HttpClientUtil.doGetForJson(fecth_customer_url + "&pageNo=0");
            dealData(jsonObject, needCustomers);

            for (int i = 1; i <= jsonObject.getInteger("totalPages"); i++) {
                jsonObject = HttpClientUtil.doGetForJson(fecth_customer_url + "&pageNo=" + i);
                dealData(jsonObject, needCustomers);
            }

            redisTemplate.opsForValue().set("needCustomer", needCustomers);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 处理数据
     */
    private void dealData(JSONObject jsonObject, List<NeedCustomer> needCustomers) {
        JSONArray jsonArray = jsonObject.getJSONArray("content");
        List<NeedCustomer> datas = JSONObject.parseArray(jsonArray.toJSONString(), NeedCustomer.class);
        for (NeedCustomer data : datas) {
            if ("customer".equals(data.getType())) {
                needCustomers.add(data);
            }
        }
    }

}
